package com.fengwk.support.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.fengwk.support.exception.BaseException;

/**
 * 工具类:正则表达式
 */
public class RegexUtils {

	public static final String MATCH_ENGLISH = "[a-z|A-Z]+";
	public static final String MATCH_CHINESE = "[\\u4e00-\\u9fa5]+";
	public static final String MATCH_ID_CARD = "\\d{17}[[0-9],0-9xX]";
	public static final String MATCH_MOBILE_PHONE = "^1[3|4|5|7|8][0-9]\\d{8}$";
	public static final String MATCH_EMAIL = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
	
	private RegexUtils() {
		throw new BaseException("can not instance " + getClass());
	}
	
	/**
	 * 英文校验
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEnglish(String str) {
		return match(str, MATCH_ENGLISH);
	}
	
	/**
	 * 中文校验
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isChinese(String str) {
		return match(str, MATCH_CHINESE);
	}
	
	/**
	 * 验证身份证格式
	 * 
	 * @param mobilePhone
	 * @return
	 */
	public static boolean isIDcard(String IDcard) {
		return match(IDcard, MATCH_ID_CARD);
	}
	
	/**
	 * 验证手机号格式
	 * 
	 * @param mobilePhone
	 * @return
	 */
	public static boolean isMobilePhone(String mobilePhone) {
		return match(mobilePhone, MATCH_MOBILE_PHONE);
	}
	
	/**
	 * 验证邮箱格式
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		return match(email, MATCH_EMAIL);
	}
	
	/**
	 * 正则查询匹配
	 * 
	 * @return
	 */
	public static boolean find(String content, String regex) {
		if(content == null || regex == null) {
			return false;
		}
		Pattern pattern = Pattern.compile(regex);
		return pattern.matcher(content).find();
	}
	
	/**
	 * 正则全匹配
	 * 
	 * @return
	 */
	public static boolean match(String content, String regex) {
		if(content == null || regex == null) {
			return false;
		}
		Pattern pattern = Pattern.compile(regex);
		return pattern.matcher(content).matches();
	}
	
	/**
	 * 捕获第一个匹配字串
	 * 
	 * @param str 需要捕获的字符串
	 * @param regex 正则表达式
	 * @return 返回捕获的String,没有则返回null
	 */
	public static String regex(String str, String regex) {
		Matcher matcher = buildMatcher(str, regex);
		while(matcher.find()) {
			return matcher.group(0);
		}
		return null;
	}
	
	/**
	 * 使用正则表达式捕获所有匹配字符数组
	 * 
	 * @param str 需要捕获的内容
	 * @param regex 正则表达式
	 * @return 返回捕获的String集合,没有则返回null
	 */
	public static List<String> regexAll(String str, String regex) {
		List<String> res = new ArrayList<String>();
		Matcher matcher = buildMatcher(str, regex);
		while(matcher.find()) {
			res.add(matcher.group(0));
		}
		if(CollectionUtils.isBlank(res)) {
			return null;
		}
		return res;
	}
	
	// 构建Matcher
	private static Matcher buildMatcher(String str, String regex) {
		return Pattern.compile(regex).matcher(str);
	}
	
}
